import ToolbarItem from "@/components/toolbar/ToolbarItem.vue";
import { i18n } from "@/locales";
import type { Editor } from "@/tiptap";
import { Extension } from "@tiptap/core";
import { markRaw } from "vue";
import RiLayoutRightLine from "~icons/ri/layout-right-line";

declare module "@/tiptap" {
  interface Commands<ReturnType> {
    sidebarToggle: {
      /**
       * Toggle sidebar visibility
       */
      toggleSidebar: () => ReturnType;
      /**
       * Set sidebar visibility
       */
      setSidebarVisibility: (visible: boolean) => ReturnType;
    };
  }
}

declare module "@tiptap/core" {
  interface Storage {
    sidebarToggle: SidebarToggleStorage;
  }
}

export interface SidebarToggleStorage {
  showSidebar: boolean;
}

const SidebarToggle = Extension.create<{}, SidebarToggleStorage>({
  name: "sidebarToggle",

  addStorage() {
    return {
      showSidebar: false,
    };
  },

  addOptions() {
    return {
      getToolbarItems({ editor }: { editor: Editor }) {
        return {
          priority: 1000,
          component: markRaw(ToolbarItem),
          props: {
            editor,
            isActive: editor.storage.sidebarToggle?.showSidebar,
            icon: markRaw(RiLayoutRightLine),
            title: i18n.global.t("editor.extensions.sidebarToggle.tooltip"),
            action: () => {
              editor.commands.toggleSidebar();
            },
          },
        };
      },
    };
  },

  addCommands() {
    return {
      toggleSidebar:
        () =>
        ({ editor }) => {
          editor.storage.sidebarToggle.showSidebar =
            !editor.storage.sidebarToggle.showSidebar;
          return true;
        },
      setSidebarVisibility:
        (visible: boolean) =>
        ({ editor }) => {
          editor.storage.sidebarToggle.showSidebar = visible;
          return true;
        },
    };
  },
});

export default SidebarToggle;
